package ruc.MongoDB.write;

import com.mongodb.client.MongoCollection;
import org.bson.Document;
import ruc.Consts.constant;
import ruc.utils.IOUtils;
import ruc.MongoDB.MongoDB_Common;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class MongoDB_DifferentRecordWrite {
    private int port;
    private String IP, dbName, tbName;

    public MongoDB_DifferentRecordWrite(String IP, int port, String dbName, String tbName) {
        this.IP = IP;
        this.port = port;
        this.dbName = dbName;
        this.tbName = tbName;
    }

    // recordLength represents records of different lengths
    void DifferentRecordLengthInsert(int[] recordLength, String[] values) {
        for (int k : recordLength) {
            long costTime = 0;
            MongoCollection<Document> collection = MongoDB_Common.GetMongoCollection(IP, port, dbName, tbName);
            collection.drop(); // 写数据前清空表
            List<Document> list = new ArrayList<>();
            int cnt = 0;
            for (String s : values) {
                String[] val = s.split(constant.Delimiter);
                cnt += s.getBytes(StandardCharsets.UTF_8).length; // 计算长度

                Document document = new Document().append("ts", val[0]).append("userInfo", val[1]).append("server", val[2])
                        .append("hostname", val[3]).append("cpu_usage", val[4]).append("memory_usage", val[5]).append("disk_usage", val[6]);

                list.add(document);
                if (cnt > k) {
                    long st_time = System.nanoTime();
                    collection.insertMany(list);
                    costTime += (System.nanoTime() - st_time) / constant.Ns2Ms;
                    list = new ArrayList<>();
                    cnt = 0;
                }
            }

            if (list.size() > 0) {
                long st_time = System.nanoTime();
                collection.insertMany(list);
                costTime += (System.nanoTime() - st_time) / constant.Ns2Ms;
            }

            System.out.printf("[TSBenchD] [MongoDB_DifferentRecordWrite] >>>>> Record Length %d Byte, Number of lines: %d 行， costTime: %d ms >>>>> \n", k, values.length, costTime);
            IOUtils.WriteData(constant.GetWriteFilePath("MongoDB", "DifferentRecordWrite"),
                    new String[]{String.valueOf(k), String.valueOf(values.length), String.valueOf(costTime)});
        }
    }

    public static void main(String[] args) {
        MongoDB_DifferentRecordWrite db = new MongoDB_DifferentRecordWrite(constant.IP, constant.MongoDB_port, constant.dbName, constant.DifferentRecordWrite_tbName);
        db.DifferentRecordLengthInsert(constant.DiffRecordLength, IOUtils.GetData());
    }
}
